<template>
	<view class="login-container">
		<!-- 替换波浪为新的顶部装饰 -->
		<view class="header-decoration"></view>

		<!-- 登录表单 -->
		<view class="form-box">
			<view class="title">{{ isLogin ? '欢迎登录' : '账号注册' }}</view>

			<!-- 输入框区域 -->
			<view class="input-group">
				<!-- 登录输入框 -->
				<view class="input-box" v-if="isLogin">
					<input type="tel" v-model="form.username" placeholder="请输入用户名" />
				</view>
				<view class="input-box" v-if="isLogin">
					<input class="uni-input" type="text" v-model="form.password" placeholder="请输入密码"
						:password="!showPassword" />
					<view @click="showPassword = !showPassword">
						<uni-icons :type="showPassword ? 'eye' : 'eye-slash'" size="30"></uni-icons>
					</view>
				</view>

				<!-- 注册输入框 -->
				<view class="input-box" v-if="!isLogin">
					<input type="mobile" v-model="form.phone" placeholder="请输入手机号" />
				</view>
				<view class="input-box" v-if="!isLogin">
					<input type="text" v-model="form.username" placeholder="请输入用户名" />
				</view>
				<view class="input-box" v-if="!isLogin">
					<input class="uni-input" type="text" v-model="form.password" placeholder="请输入密码"
						:password="!showPassword" />
					<view @click="showPassword = !showPassword">
						<uni-icons :type="showPassword ? 'eye' : 'eye-slash'" size="30"></uni-icons>
					</view>
				</view>
				<view class="input-box" v-if="!isLogin">
					<input class="uni-input" type="text" v-model="form.confirmPassword" placeholder="请确认密码"
						:password="!showPassword" />
					<view @click="showPassword = !showPassword">
						<uni-icons :type="showPassword ? 'eye' : 'eye-slash'" size="30"></uni-icons>
					</view>
				</view>

				<!-- 隐私政策确认 -->
				<view class="privacy-box">
					<checkbox-group @change="(e) => form.agreePrivacy = e.detail.value.length > 0">
						<checkbox :checked="form.agreePrivacy" style="transform:scale(0.7)" />
					</checkbox-group>
					<text class="privacy-text">我已阅读并同意</text>
					<text class="privacy-link" @click="showToast('隐私政策')">《隐私政策》</text>
				</view>
			</view>

			<!-- 按钮区域 -->
			<view class="btn-group">
				<button class="submit-btn" @click="submit">
					{{ isLogin ? '登 录' : '注 册' }}
				</button>
				<view class="action-links">
					<text class="forget-pwd" v-if="isLogin" @click="handleForgetPassword">忘记密码？</text>
					<text class="switch-type" @click="switchLoginType">
						{{ isLogin ? '没有账号？去注册' : '已有账号？去登录' }}
					</text>
				</view>
			</view>
		</view>
	</view>
</template>

<script setup lang="ts">
	// 导入
	// 第三方库
	import CryptoJS from 'crypto-js'
	
	// Vue 相关
	import { onLoad } from '@dcloudio/uni-app'
	import { ref, computed } from 'vue'
	
	// 类型导入
	import type { LoginParams, RegisterParams } from '@/types'
	
	// 项目内部模块
	import { SECRET_KEY } from '@/utils/config'
	import { getToken, getUserInfos, registerUser, clearUser } from '@/stores/user'
	import { getThemeStyles } from '@/stores/theme'
	
	// 响应式数据
	const showPassword = ref(false)
	const isLogin = ref(true)
	const form = ref({
		phone: '18156548135',
		username: 'zhangboyi',
		password: '123456',
		confirmPassword: '123456',
		agreePrivacy: true
	})

	// 计算属性
	const themeStyles = computed(() => getThemeStyles());

	// 工具方法 - 保留复杂的加密方法
	const encryptPassword = (password: string) => {
		const CRYPTO_KEY = CryptoJS.enc.Utf8.parse(SECRET_KEY)
		const encrypted = CryptoJS.AES.encrypt(password, CRYPTO_KEY, {
			iv: CRYPTO_KEY,
			mode: CryptoJS.mode.CFB,
			padding: CryptoJS.pad.NoPadding
		})
		return encrypted.toString()
	}

	// 业务逻辑方法
	const switchLoginType = () => {
		isLogin.value = !isLogin.value
		// 重置表单数据
		form.value = {
			phone: form.value.phone,
			username: form.value.username,
			password: form.value.password,
			confirmPassword: form.value.confirmPassword,
			agreePrivacy: form.value.agreePrivacy
		}
	}
	// 清理缓存token
	const clearToken = async () => {
		// 前端token缓存清除
		await clearUser()
	}
	// 登录方法
	const login = async () => {
		// await clearToken()
		console.log("login")
		// 1.隐私政策验证
		if (!form.value.agreePrivacy) {
			uni.showToast({
			title: '请同意隐私政策',
			icon: 'none',
			duration: 2000
		});
			return
		}

		// 2.密码加密 - 暂时禁用加密进行测试
		const encPassword = encryptPassword(form.value.password)
		// const encPassword = form.value.password // 使用明文密码测试

		// 3.构造登录参数
		const loginParams: LoginParams = {
			username: form.value.username,
			password: encPassword,
			grant_type: 'password',
			scope: 'server',
		}

		// 4.获取token
		await getToken(loginParams)

		// 5.查询个人信息
		await getUserInfos()

		// 6.登录成功提示
		uni.showToast({
			title: '登录成功',
			icon: 'none',
			duration: 2000
		});

		// 7.跳转到首页
		uni.switchTab({
				url: '/pages/index/index'
			});
	}
	// 注册方法
	const register = async () => {
		console.log("register")
		
		// 1.表单验证
		if (!form.value.username || !form.value.password || !form.value.phone) {
			uni.showToast({
				title: '请填写完整信息',
				icon: 'none',
				duration: 2000
			});
			return
		}

		if (!form.value.agreePrivacy) {
			uni.showToast({
				title: '请同意隐私政策',
				icon: 'none',
				duration: 2000
			});
			return
		}

		try {
			// 2.构造注册参数
			const registerParams: RegisterParams = {
				username: form.value.username,
				password: form.value.password,
				phone: form.value.phone
			}

			// 3.执行注册
			await registerUser(registerParams)

			// 4.切换到登录页（注册成功提示已在registerUser中处理）
			switchLoginType()
		} catch (error) {
			// 错误处理已在registerUser中处理
			console.error('注册失败:', error)
		}
	}

	// 忘记密码处理
	const handleForgetPassword = () => {
		uni.navigateTo({
			url: '/pages/login/forget-password'
		});
	}

	// 页面交互方法
	const submit = async () => {
		if (isLogin.value) {
			await login()
		} else {
			await register()
		}
	}

	// 生命周期
	onLoad(async () => {
		// 清理缓存token
		// await clearToken()

		// 自动登录
		// await login()
	})
</script>
<style lang="scss">
	/* stylelint-disable */
	.login-container {
		position: relative;
		display: flex;
		flex-direction: column;
		min-height: 100vh;
		background: #f5f6fa;
		padding: 0 40rpx;

	}

	// 删除旧的.wave-box相关样式，添加新的顶部装饰样式
	.header-decoration {
		height: 480rpx;
		background: v-bind('themeStyles.primaryGradient');
		margin: 0 -40rpx;
		position: relative;

		&::after {
			content: '';
			position: absolute;
			bottom: -60rpx;
			left: 0;
			right: 0;
			height: 120rpx;
			background: #f5f6fa;
			border-radius: 50% 50% 0 0;
			transform: scaleX(1.5);
		}
	}

	.form-box {
		margin-top: -120rpx;
		background: rgba(255, 255, 255, 0.95);
		border-radius: 30rpx;
		padding: 60rpx 60rpx;
		box-shadow: v-bind('themeStyles.cardBoxShadow');
		backdrop-filter: blur(10px);
		border: 1px solid rgba(255, 255, 255, 0.9);

		.title {
			font-size: 40rpx;
			font-weight: 600;
			text-align: center;
			margin-bottom: 80rpx;
			background: v-bind('themeStyles.primaryGradient');
			background-clip: text;
			-webkit-background-clip: text;
			color: transparent;
			text-shadow: 2rpx 2rpx 4rpx rgba(0, 0, 0, 0.05);
		}
	}

	.input-group {
		margin: 0;

		.input-box {
			display: flex;
			align-items: center;
			background: rgba(255, 255, 255, 0.95);
			border-radius: 16rpx;
			margin-bottom: 40rpx;
			padding: 24rpx 40rpx;
			box-shadow: v-bind('themeStyles.shadowSm');
			border: 1px solid v-bind('themeStyles.borderLight');
			transition: all 0.3s ease;

			&:last-child {
				margin-bottom: 20rpx;
			}

			input {
				flex: 1;
				font-size: 28rpx;
				color: v-bind('themeStyles.textPrimary');
				padding: 4rpx 0;

				&::placeholder {
					color: v-bind('themeStyles.textPlaceholder');
				}
			}
		}

		.code-box {
			position: relative;

			.code-btn {
				position: absolute;
				right: 40rpx;
				color: v-bind('themeStyles.primaryColor');
				font-size: 26rpx;
				padding: 10rpx 0 10rpx 30rpx;
				border-left: 1px solid v-bind('themeStyles.border');

				&.disabled {
					color: v-bind('themeStyles.textPlaceholder');
				}
			}
		}
	}

	.btn-group {
		margin-top: 50rpx;
		padding: 0;

		.submit-btn {
			background: v-bind('themeStyles.primaryGradient');
			color: #fff;
			border: none;
			border-radius: 50rpx;
			font-size: 30rpx;
			font-weight: 500;
			letter-spacing: 8rpx;
			box-shadow: v-bind('themeStyles.buttonBoxShadow');
			transition: all 0.3s ease;
			width: 85%;
			margin: 0 auto;



			&:active {
				transform: translateY(2rpx);
				box-shadow: v-bind('themeStyles.cardBoxShadow');
				opacity: 0.95;
			}
		}

		.action-links {
			display: flex;
			justify-content: center;
			align-items: center;
			margin-top: 40rpx;

			.forget-pwd {
				font-size: 26rpx;
				color: v-bind('themeStyles.primaryColor');
				padding: 20rpx;
				margin-right: 40rpx;

				&:active {
					opacity: 0.8;
				}
			}

			.switch-type {
				font-size: 26rpx;
				color: v-bind('themeStyles.primaryColor');
				padding: 20rpx;

				&:active {
					opacity: 0.8;
				}
			}
		}
	}

	.privacy-box {
		display: flex;
		align-items: center;
		padding: 0 20rpx;
		margin-top: -20rpx;

		.privacy-text {
			font-size: 24rpx;
			color: v-bind('themeStyles.textSecondary');
			margin-left: -10rpx;
		}

		.privacy-link {
			font-size: 24rpx;
			color: v-bind('themeStyles.primaryColor');
		}
	}
</style>